package com.silence.springboot.dao;

import com.mybatisflex.core.query.QueryWrapper;
import com.silence.springboot.dto.UserRoleJoinRoleDto;
import com.silence.springboot.mapper.UserRoleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.List;

import static com.silence.springboot.entity.table.RoleEntityTableDef.ROLE_ENTITY;
import static com.silence.springboot.entity.table.UserRoleEntityTableDef.USER_ROLE_ENTITY;

@Slf4j
@Repository
@RequiredArgsConstructor
public class UserRoleDao {

    /**
     * 用户角色关联表 Mapper 接口
     */
    private final UserRoleMapper userRoleMapper;

    /**
     * 查询用户角色关联表
     *
     * @return 用户角色关联表
     */
    public List<UserRoleJoinRoleDto> selectUserRoleJoinRole(List<Long> userIds) {
        QueryWrapper query = QueryWrapper.create()
                .select(USER_ROLE_ENTITY.USER_ID, USER_ROLE_ENTITY.ROLE_ID)
                .select(ROLE_ENTITY.ROLE_CODE, ROLE_ENTITY.ROLE_NAME, ROLE_ENTITY.ROLE_DESC)
                .from(USER_ROLE_ENTITY)
                .leftJoin(ROLE_ENTITY)
                .on(USER_ROLE_ENTITY.ROLE_ID.eq(ROLE_ENTITY.ID))
                .where(USER_ROLE_ENTITY.USER_ID.in(userIds))
                .orderBy(ROLE_ENTITY.ID.asc());
        return userRoleMapper.selectListByQueryAs(query, UserRoleJoinRoleDto.class);
    }

    /**
     * 删除用户角色关联表
     *
     * @param userId 用户id
     */
    public void deleteUserRoleByUserId(long userId) {
        QueryWrapper query = QueryWrapper.create()
                .from(USER_ROLE_ENTITY)
                .where(USER_ROLE_ENTITY.USER_ID.eq(userId));
        userRoleMapper.deleteByQuery(query);
    }

}
